package com.xianggu.spring.aop.config;

import com.xianggu.spring.aop.joinPoint.InterFaceJoinPoint;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author chengjy
 * @date 2025/3/10
 */
public class AopCglibProxyFactory implements MethodInterceptor {


    private Object target;
    private Advice advice;


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        try{
            InterFaceJoinPoint joinPoint = new InterFaceJoinPoint(method, objects, target);

            // 跳过toString方法
            if("toString".equals(method.getName())){
                return methodProxy.invokeSuper(o , objects);
            }
            // 前置增强
            advice.before(joinPoint);

            // 执行原始方法
            Object result = methodProxy.invokeSuper(o , objects);

            // 后置增强
            advice.after(joinPoint);
            return result;
        }catch (RuntimeException e){
            advice.afterThrowing(method, e);
            throw e;
        }finally {
            // 最终增强
            advice.afterReturning(method, null);
        }
    }


    public AopCglibProxyFactory(Object target, Advice advice) {
        this.target = target;
        this.advice = advice;
    }
}
